package common

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type R[T any] struct {
	Ctx          *gin.Context
	responseBody map[string]any
}

func NewResponseBuilder[T any](ctx *gin.Context) *R[T] {
	return &R[T]{
		Ctx: ctx,
		responseBody: map[string]any{
			"code":    200,
			"message": "success",
		}}
}

func (r *R[T]) Code(code int) *R[T] {
	r.responseBody["code"] = code
	return r
}

func (r *R[T]) Message(msg string) *R[T] {
	r.responseBody["message"] = msg
	return r
}

func (r *R[T]) ErrorMessage(err error) *R[T] {
	r.responseBody["code"] = 500
	r.responseBody["message"] = fmt.Sprintf("error occur: %s\n", err)
	return r
}

func (r *R[T]) Data(data T) *R[T] {
	r.responseBody["data"] = data
	return r
}

func (r *R[T]) Response() {
	r.Ctx.JSON(http.StatusOK, r.responseBody)
}
